//package com.test.learnkotlin.ui.activity
//
//import android.Manifest
//import android.content.Context
//import android.content.Intent
//import android.content.pm.PackageManager
//import android.content.res.Configuration
//import android.graphics.BitmapFactory
//import android.graphics.Color
//import android.graphics.drawable.ColorDrawable
//import android.media.MediaScannerConnection
//import android.net.Uri
//import android.os.Build
//import android.os.Bundle
//import android.os.PersistableBundle
//import android.util.Log
//import android.util.Size
//import android.view.SoundEffectConstants
//import android.view.Surface
//import android.view.ViewGroup
//import android.webkit.MimeTypeMap
//import android.widget.Button
//import android.widget.ImageView
//import android.widget.PopupWindow
//import androidx.camera.core.*
//import androidx.camera.lifecycle.ProcessCameraProvider
//import androidx.camera.view.PreviewView
//import androidx.core.app.ActivityCompat
//import androidx.core.content.ContextCompat
//import androidx.core.net.toFile
//import androidx.lifecycle.Lifecycle
//import androidx.lifecycle.LifecycleRegistry
//import com.google.common.util.concurrent.ListenableFuture
//import com.test.learnkotlin.BR
//import com.test.learnkotlin.R
//import com.test.learnkotlin.base.BaseActivity
//import com.test.learnkotlin.databinding.ActivityCameraxBinding
//import com.test.learnkotlin.main
//import com.test.learnkotlin.utils.LogUitls
//import com.test.learnkotlin.viewmodel.TestCameraXViewModel
//import java.io.File
//import java.text.SimpleDateFormat
//import java.util.*
//import java.util.concurrent.ExecutorService
//import java.util.concurrent.Executors
//
///*
//
//关于Http协议的知识总结
//https://sunnyboy.blog.csdn.net/article/details/104475472?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-3-104475472-blog-107740275.t5_layer_targeting_s_randoms&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-3-104475472-blog-107740275.t5_layer_targeting_s_randoms&utm_relevant_index=4
//
//Android camera2 实现相机预览及获取预览帧数据流
//https://blog.csdn.net/ganfanzhou/article/details/83721750?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3-83721750-blog-122143560.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3-83721750-blog-122143560.pc_relevant_aa&utm_relevant_index=5
//
//Camera2】Android Camera2 综述
//https://blog.csdn.net/Scott_S/article/details/122143560
//
//Android Media 07 --- Camera2
//https://www.jianshu.com/p/a06883b8f713
//
//Android Camera2 教程 · 第四章 · 拍照
//https://www.jianshu.com/p/2ae0a737c686
//
//
//CameraX 架构
//https://developer.android.google.cn/training/camerax/architecture#kotlin
//
//CameraX
//https://developer.android.google.cn/jetpack/androidx/releases/camera?hl=en
//
//
//Android 使用CameraX实现预览/拍照/录制视频/图片分析/对焦/切换摄像头等操作
//https://blog.csdn.net/EthanCo/article/details/125603671
//
//
//本文使用下面链接
//使用Camera X遇到的坑_OnPause时没有释放相机导致回来时黑屏
//https://blog.csdn.net/cjzjolly/article/details/124293800
//
//
//
// */
//class TestCameraXActivity2 : BaseActivity<TestCameraXViewModel, ActivityCameraxBinding>() {
//    private var mCameraPRrovider: ProcessCameraProvider? = null
//    private var mLensFacing: Int = CameraSelector.LENS_FACING_BACK
//    private var mPreviewView: PreviewView? = null
//    private var mLifecycleRegistry: LifecycleRegistry? = null
//
//    /**拍照器**/
//    private var mImageCapture: ImageCapture? = null
//    private var mTakePhotoExecutor: ExecutorService? = null
//    private var mBtnTakePhoto: Button? = null
//    private var mImagePhoto: ImageView? = null
//    private var mPreview: Preview? = null
//    private var mBtnFlashLight: Button? = null
//
//    override fun getContentLayoutId(): Int = R.layout.activity_camerax2
//
//    override fun variableId(): Int = BR.mTestCameraXViewModel
//
//    override fun initView() {
//        super.initView()
//        //拍照专用线程，让它不要卡住主线程:
//        mTakePhotoExecutor = Executors.newSingleThreadExecutor()
//        //权限申请
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this,  arrayOf(Manifest.permission.CAMERA), 1);
//        }
//
//        mLifecycleRegistry = LifecycleRegistry(this)
////        mLifecycleRegistry!!.markState(Lifecycle.State.CREATED)
//        mLifecycleRegistry!!.currentState = Lifecycle.State.CREATED
//
//        mBtnFlashLight = findViewById(R.id.btn_flash_light)
//        mPreviewView = findViewById(R.id.pv)
//        mBtnTakePhoto = findViewById(R.id.btn_take_photo)
//        mImagePhoto = findViewById(R.id.iv_photo)
//
//
//    }
//
//    override fun initEvent() {
//        super.initEvent()
//
//        mBtnTakePhoto?.setOnClickListener{
//            takePhoto(mImageCapture!!)
//        }
//
//        mBtnFlashLight?.setOnClickListener {
//            when(it.tag){
//                "auto" ->{
//                    mImageCapture?.setFlashMode(ImageCapture.FLASH_MODE_ON)
//                    (it as Button).setText("闪光灯:常开")
//                    it.setTag("on")
//                }
//
//                "on" ->{
//                    mImageCapture?.setFlashMode(ImageCapture.FLASH_MODE_OFF)
//                    (it as Button).setText("闪光灯:关闭")
//                    it.setTag("off")
//                }
//                else ->{
//                    mImageCapture?.setFlashMode(ImageCapture.FLASH_MODE_AUTO)
//                    (it as Button).setText("闪光灯:自动")
//                    it.setTag("auto")
//                }
//
//            }
//
//        }
//
//    }
//
//    override fun onConfigurationChanged(newConfig: Configuration) {
//        super.onConfigurationChanged(newConfig)
//        LogUitls.i("生命周期 -- onConfigurationChanged")
//    }
//
//    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
//        super.onSaveInstanceState(outState, outPersistentState)
//        LogUitls.i("生命周期 -- onSaveInstanceState")
//
//    }
//
//    override fun onStart() {
//        super.onStart()
//        LogUitls.i("生命周期 -- onStart")
//
//        mLifecycleRegistry!!.currentState = Lifecycle.State.STARTED
//    }
//
//    override fun onResume() {
//        super.onResume()
//        LogUitls.i("生命周期 -- onResume")
//
//        val processCameraProvider: ListenableFuture<ProcessCameraProvider> = ProcessCameraProvider.getInstance(this)
//        //回来的时候要重新绑定一下
//        processCameraProvider.addListener({
//
//            try {
//                mCameraPRrovider = processCameraProvider.get()
//                //绑定预览窗等
//                bindCameraUseCases(mCameraPRrovider!!)
//            } catch (e: Exception) {
//                LogUitls.i("cameraProviderFuture 发生异常：${e}")
//            }
//
//        },ContextCompat.getMainExecutor(this))//只能在主线程
//
//        mLifecycleRegistry!!.currentState = Lifecycle.State.RESUMED
//    }
//
//    override fun onRestart() {
//        super.onRestart()
//        LogUitls.i("生命周期 -- onRestart")
//
//    }
//
//    override fun onPause() {
//        super.onPause()
//        LogUitls.i("生命周期 -- onPause")
//        //出去的时候要释放相机资源
//        mCameraPRrovider!!.unbindAll()
//
//    }
//
//
//    override fun onStop() {
//        super.onStop()
//        LogUitls.i("生命周期 -- onStop")
//
//    }
//
//    override fun onDestroy() {
//        super.onDestroy()
//        LogUitls.i("生命周期 -- onDestroy")
//        mLifecycleRegistry!!.currentState = Lifecycle.State.DESTROYED
//        mTakePhotoExecutor!!.shutdown()
//
//    }
//
////    override fun getLifecycle():Lifecycle = mLifecycleRegistry!!
//
//    private fun hasBackCamera():Boolean{
//        try {
//            return mCameraPRrovider!!.hasCamera(CameraSelector.DEFAULT_BACK_CAMERA)
//        } catch (e: Exception) {
//            LogUitls.i("后置 hasBackCamera 发生异常：$e")
//        }
//
//        return false
//    }
//
//    private fun hasFrontCamera():Boolean{
//        try {
//            return mCameraPRrovider!!.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)
//        } catch (e: Exception) {
//            LogUitls.i("前置 hasFrontCamera 发生异常：$e")
//        }
//
//        return false
//    }
//
//    private fun bindCameraUseCases(cameraProvider: ProcessCameraProvider, surface: Surface? = null){
//        val aspectRatio = AspectRatio.RATIO_4_3
//        mPreview = Preview.Builder()
//            .setTargetAspectRatio(aspectRatio)
////            .setTargetRotation(mPreviewView!!.display.rotation)
//            .build()
//
//        //为预览窗口添加surface通道
//        mPreview!!.setSurfaceProvider(mPreviewView!!.surfaceProvider)
//        //照片抓取:
//        mImageCapture = ImageCapture.Builder()
//            .setTargetAspectRatio(aspectRatio)
//            //低延迟拍照，反应速度会比较快
//            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
////            .setTargetRotation(mPreviewView!!.display.rotation)
//            .setFlashMode(ImageCapture.FLASH_MODE_AUTO)//闪光灯调节
//            .build()
//
//        val imageAnalysis = ImageAnalysis
//            .Builder()
//            .setTargetAspectRatio(aspectRatio)
////            .setTargetRotation(mPreviewView!!.display.rotation)
//            .build()
//
//        //解绑之前可能存在的绑定关系
//        cameraProvider.unbindAll()
//        //有后置摄像头就选后置，否则用前置
//        if (hasBackCamera()) {
//            mLensFacing = CameraSelector.LENS_FACING_BACK
//        }
//
//        if (hasFrontCamera()) {
////            mLensFacing = CameraSelector.LENS_FACING_FRONT
//        }else{
//            throw IllegalStateException("前后摄像头都没")
//        }
//
//        val cameraSelector = CameraSelector.Builder().requireLensFacing(mLensFacing).build()
//        //绑定生命周期、预览窗、拍照获取器等
//        cameraProvider.bindToLifecycle(this, cameraSelector, mPreview, mImageCapture, imageAnalysis)
//    }
//
//    private fun takePhoto(imageCapture: ImageCapture){
//        if (imageCapture == null){
//            LogUitls.i("imageCapture is null")
//            return
//        }
//
//        val fileFormatPattern = "yyyy-MM-dd-HH-mm-ss-SSS"
//        val simpleDateFormat = SimpleDateFormat(fileFormatPattern)
//
//        //先存放到APP本地文件夹:
////        val cacheFileDir: File = getCacheDir(); //APP内cache地址
//        val cacheFileDir: File? = getExternalCacheDir() //共用的、大家都可以访问的cache地址
//        if (cacheFileDir!!.exists() && cacheFileDir!!.isDirectory()){
//            val newFile = File(cacheFileDir.getAbsolutePath() + String.format("/%s.jpg", simpleDateFormat.format(System.currentTimeMillis())))
//            LogUitls.i("图片路径：${newFile.absolutePath}")
//            newFile.createNewFile()
//            if (!newFile.exists()) {
//                return
//            }
//
//            val outputOptions = ImageCapture.OutputFileOptions.Builder(newFile)
//                .setMetadata(ImageCapture.Metadata())
//                .build()
//            //照片拍好之后从回调里面接收
//            imageCapture.takePicture(outputOptions, mTakePhotoExecutor!!,object : ImageCapture.OnImageSavedCallback{
//                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
//                   val savedUri = if (outputFileResults.getSavedUri() == null) Uri.fromFile(newFile) else outputFileResults.getSavedUri()
//                    //给按钮弄个照片
//                    runOnUiThread{
//                        if (newFile.exists()) {
//                            mImagePhoto!!.setImageBitmap(BitmapFactory.decodeFile(newFile.absolutePath))
//                        }
//                    }
//
//
//                    // We can only change the foreground Drawable using API level 23+ API
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                        // Update the gallery thumbnail with latest picture taken
////                            setGalleryThumbnail(savedUri);
//                    }
//
//                    // Implicit broadcasts will be ignored for devices running API level >= 24
//                    // so if you only target API level 24+ you can remove this statement
//                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//                        sendBroadcast(Intent(android.hardware.Camera.ACTION_NEW_PICTURE, savedUri))
//                    }
//                    // If the folder selected is an external media directory, this is
//                    // unnecessary but otherwise other apps will not be able to access our
//                    // images unless we scan them using [MediaScannerConnection]
//                    val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".jpg")
//                    MediaScannerConnection.scanFile(this@TestCameraXActivity2,
//                        arrayOf(savedUri!!.getPath()),
//                        arrayOf(mimeType),
//                        object : MediaScannerConnection.OnScanCompletedListener {
//
//                            override fun onScanCompleted(path: String?, uri: Uri?) {
//                                LogUitls.i( "新文件扫描完成, 文件大小: ${newFile.length()}   ${newFile.length() / 1024 / 1024} M")
//
//                            }
//                        })
//
//                }
//
//                override fun onError(exception: ImageCaptureException) {
//                    LogUitls.i("takePicture 发生异常：${exception}")
//
//                }
//            })
//
//        }
//
//    }
//
//}